package com.fancon.android.hotgirlcollection;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.fancon.android.activity.FanconBaseActivity;
import com.fancon.android.cache.utils.StorageUtils;
import com.fancon.android.multithread.RequestUI;
import com.fancon.android.ui.widget.FanconProgressBar;
import com.fancon.android.xchannel.entity.Photo;
import com.google.ads.AdRequest;
import com.google.ads.AdView;

public class PhotoDetailActivity extends FanconBaseActivity implements
		OnClickListener {
	private static final String RAGE_VIET_PREF = "XChannel";
	private String photoUrl;
	private WebView mWb;

	private String imagePath;
	private int shareMenu = Menu.FIRST;
	private int saveMenu = Menu.FIRST + 1;
	private int refreshMenu = Menu.FIRST + 2;
	private int wallPaper = Menu.FIRST + 3;
	private int group2Id = 1;

	private String lastSaveName = "";
	private SharedPreferences mPrefs = null;

	//
	private int index = 0;
	private String jsonList;
	private ArrayList<Photo> lisPhoto;
	private ImageView next, back;
	private int imgWidth = 480;
	private int imgHeight = 800;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(group2Id, shareMenu, shareMenu,
				getResources().getString(R.string.share)).setIcon(
				R.drawable.ic_menu_share);
		menu.add(group2Id, saveMenu, saveMenu,
				getResources().getString(R.string.save)).setIcon(
				R.drawable.ic_menu_save);
		menu.add(group2Id, refreshMenu, refreshMenu,
				getResources().getString(R.string.refresh)).setIcon(
				R.drawable.ic_menu_refresh);
		menu.add(group2Id, wallPaper, wallPaper,
				getResources().getString(R.string.set_wall_paper)).setIcon(
				R.drawable.wpp);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case Menu.FIRST:
			// shareImage();
			doShare();
			break;
		case Menu.FIRST + 1:
			saveImage();
			break;
		case Menu.FIRST + 2:
			refresh();
			break;
		case Menu.FIRST + 3:
			// doAbout();
			doWallPaper();
			break;

		}
		return true;
	}

	private void saveImage() {
		AlertDialog.Builder salert = new AlertDialog.Builder(this);

		salert.setTitle(R.string.select_name);
		// Set an EditText view to get user input
		final EditText sinput = new EditText(this);
		sinput.setText(lastSaveName);
		salert.setView(sinput);

		salert.setPositiveButton(getResources().getString(R.string.ok),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						doSave(sinput.getText().toString(), false);
					}
				});

		salert.setNegativeButton(getResources().getString(R.string.cancel),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
					}
				});

		salert.show();
	}

	private Bitmap loadBitMap(String filrPath) {
		return BitmapFactory.decodeFile(filrPath);
	}

	private void doSave(String fname, boolean doShare) {
		CharSequence text = getResources().getString(R.string.image_saved_as)
				+ " ";
		try {
			String ReservedChars = "|\\?*<\":>+[]/'";
			for (char c : ReservedChars.toCharArray()) {
				fname = fname.replace(c, '_');
			}
			String value = fname;
			Bitmap b = loadBitMap(imagePath);
			if (b == null) {
				text = getResources().getString(R.string.image_save_fail_1);
				;
				Toast.makeText(this, text, Toast.LENGTH_LONG).show();
				return;
			}
			File folder = getFilesDir();
			if (externalStorageAvailable()) {
				try {
					folder = Environment
							.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
					if (!folder.exists() || !folder.canWrite()) {
						folder = Environment
								.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
					}
					if (!folder.exists() || !folder.canWrite()) {
						folder = Environment.getExternalStorageDirectory();
					}
				} catch (Exception e) {
					folder = Environment.getExternalStorageDirectory();
				} catch (Error e) {
					folder = Environment.getExternalStorageDirectory();
				}
				if (!folder.exists() || !folder.canWrite()) {
					folder = getFilesDir();
				}
			}
			/*
			 * String folder =
			 * Environment.getExternalStorageDirectory().toString() +
			 * "/Pictures"; try { folder =
			 * Environment.getExternalStoragePublicDirectory
			 * (Environment.DIRECTORY_PICTURES).toString(); } catch
			 * (NoSuchFieldError e) {
			 * 
			 * }
			 */
			String ext = ".jpg";
			if (mPrefs.getString("format", "JPG").equals("PNG"))
				ext = ".png";
			String fullname = folder.getAbsolutePath() + File.separator + value
					+ ext;
			Map<String, String> hm = new HashMap<String, String>();
			hm.put("filename", fullname);
			FileOutputStream fos;
			if (folder == getFilesDir())
				fos = openFileOutput(value + ext, Context.MODE_WORLD_WRITEABLE);
			else {
				File f2 = new File(fullname);// openFileOutput(fname,
												// Context.MODE_PRIVATE);//new
												// FileOutputStream(fullname);
				fos = new FileOutputStream(f2);
			}
			if (ext.equals(".png"))
				b.compress(CompressFormat.PNG, 95, fos);
			else
				b.compress(CompressFormat.JPEG, 95, fos);
			fos.close();
			String[] str = new String[1];
			str[0] = fullname;
			if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO) {
				MediaScannerConnection.scanFile(this, str, null, null);
			}
			text = text + value + ext + " "
					+ getResources().getString(R.string.saved_end);
			;
			lastSaveName = value;
			// setDetailTitle ();
			if (doShare) {
				// FlurryAgent.logEvent("Share start");
				Intent share = new Intent(Intent.ACTION_SEND);
				if (ext.equals(".png"))
					share.setType("image/png");
				else
					share.setType("image/jpeg");

				share.putExtra(Intent.EXTRA_STREAM,
						Uri.parse("file://" + fullname.replace(" ", "%20")));
				share.putExtra(Intent.EXTRA_TITLE, value);

				startActivity(Intent.createChooser(share, getResources()
						.getString(R.string.share_image)));
			}
		} catch (Exception e) {
			Map<String, String> hm = new HashMap<String, String>();
			hm.put("text", e.toString());
			e.printStackTrace();
			text = getResources().getString(R.string.image_save_fail_2)
					+ e.toString();
		} catch (Error e) {
			Map<String, String> hm = new HashMap<String, String>();
			hm.put("text", e.toString());
			e.printStackTrace();
			text = getResources().getString(R.string.image_save_fail_2)
					+ e.toString();
		}
		Toast.makeText(this, text, Toast.LENGTH_LONG).show();
	}

	private boolean externalStorageAvailable() {
		boolean mExternalStorageAvailable;
		boolean mExternalStorageWriteable;
		String state = Environment.getExternalStorageState();

		if (state.equals(Environment.MEDIA_MOUNTED)) {
			// We can read and write the media
			mExternalStorageAvailable = mExternalStorageWriteable = true;
		} else if (state.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
			// We can only read the media
			mExternalStorageAvailable = true;
			mExternalStorageWriteable = false;
		} else {
			// Something else is wrong. It may be one of many other states, but
			// all we need
			// to know is we can neither read nor write
			mExternalStorageAvailable = mExternalStorageWriteable = false;
		}
		return mExternalStorageAvailable && mExternalStorageWriteable;
	}

	private void refresh() {
		mWb.clearHistory();
		mWb.clearView();
		DownloadPhotoRequest allRageRequest = new DownloadPhotoRequest(
				"downloadphoto", this, photoUrl);
		getGlobalState().getRequestQueue().addRequest(allRageRequest);
	}

	private void shareImage() {
		Intent sharingIntent = new Intent(Intent.ACTION_SEND);

		Uri screenshotUri = Uri.parse(this.imagePath);
		sharingIntent.setType("image/png");
		sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
		startActivity(Intent.createChooser(sharingIntent, "Share image using"));
	}

	private void doWallPaper() {
		try {
			FileInputStream is = new FileInputStream(new File(imagePath));
			BufferedInputStream bis = new BufferedInputStream(is);
			Bitmap bitmap = BitmapFactory.decodeStream(bis);
			Bitmap useThisBitmap = Bitmap.createScaledBitmap(bitmap,
					mWb.getWidth(), mWb.getHeight(), true);
			bitmap.recycle();
			if (imagePath != null) {
				WallpaperManager wallpaperManager = WallpaperManager
						.getInstance(this);
				Drawable wallpaperDrawable = wallpaperManager.getDrawable();
				wallpaperManager.setBitmap(useThisBitmap);
			}
			Toast.makeText(this, getString(R.string.set_wall_paper_success),
					1000).show();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			Toast.makeText(this, getString(R.string.set_wall_paper_false), 1000)
					.show();
		}
	}

	private void doAbout() {
		try {
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setData(Uri.parse("market://search?q=pub:Fancon+Software"));
			startActivity(intent);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	private void doShare() {
		if (lastSaveName == "") {
			AlertDialog.Builder alert = new AlertDialog.Builder(this);
			alert.setTitle(R.string.select_name);
			final EditText input = new EditText(this);
			alert.setView(input);
			alert.setPositiveButton(getResources().getString(R.string.ok),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							doSave(input.getText().toString(), true);
						}
					});

			alert.setNegativeButton(getResources().getString(R.string.cancel),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
						}
					});

			alert.show();
		} else {
			doSave(lastSaveName, true);
		}
	}

	private void copyFile(InputStream in, OutputStream out) throws IOException {
		byte[] buffer = new byte[1024];
		int read;
		while ((read = in.read(buffer)) != -1) {
			out.write(buffer, 0, read);
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		try {
			requestWindowFeature(Window.FEATURE_NO_TITLE);
			setContentView(R.layout.photo_detail);
			next = (ImageView) findViewById(R.id.next_btn);
			back = (ImageView) findViewById(R.id.back_btn);
			next.setOnClickListener(this);
			back.setOnClickListener(this);
			mWb = (WebView) findViewById(R.id.rage_detail);
			Bundle extras = getIntent().getExtras();
			mWb.getSettings().setBuiltInZoomControls(true);
			// mWb.getSettings().setUseWideViewPort(true);
			try {
				if (extras != null) {
					photoUrl = extras.getString("photoUrl");
					Log.d("photo id", photoUrl);
					index = extras.getInt("index");
					jsonList = extras.getString("listPhoto");
				}
				lisPhoto = getPhoto(jsonList);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}

			AdView adview = (AdView) findViewById(R.id.adView);
			AdRequest re = new AdRequest();
			//re.setTesting(true);
			re.setGender(AdRequest.Gender.FEMALE);
			adview.loadAd(re);
			mPrefs = getSharedPreferences(RAGE_VIET_PREF, 0);
			loadImage();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	private void loadImage() {
		if (photoUrl != null) {
			String filename = String.valueOf(photoUrl.hashCode());
			String base = Environment.getExternalStorageDirectory()
					.getAbsolutePath().toString();
			File file = new File(StorageUtils.getIndividualCacheDirectory(
					getApplicationContext()).getAbsolutePath()
					+ "/" + filename);
			if (file.exists()) {
				imagePath = StorageUtils.getIndividualCacheDirectory(
						getApplicationContext()).getAbsolutePath()
						+ "/" + filename;
				String html = "<html><head></head><body><center><img src=\""
						+ "file:/" + imagePath + "\"></center></body></html>";
				mWb.loadDataWithBaseURL("", html, "text/html", "utf-8", "");
			} else {
				DownloadPhotoRequest allRageRequest = new DownloadPhotoRequest(
						"downloadphoto", this, photoUrl);
				getGlobalState().getRequestQueue().addRequest(allRageRequest);
			}
		}
	}

	private ArrayList<Photo> getPhoto(String result) throws JSONException,
			UnsupportedEncodingException {
		// Photo[] photos = (Photo[])decode(is, Photo[].class);
		ArrayList<Photo> photos = new ArrayList<Photo>();
		JSONArray jobjects = new JSONArray(result);
		JSONObject phoJson = null;
		for (int i = 0; i < jobjects.length(); i++) {
			phoJson = jobjects.getJSONObject(i);
			Photo photo = new Photo();
			if (phoJson.opt("id") != null) {
				photo.setId(phoJson.getLong("id"));
			}
			if (phoJson.opt("title") != null) {
				photo.setTitle(URLDecoder.decode(phoJson.getString("title"),
						"UTF-8"));
			}
			if (phoJson.opt("thumbUrl") != null) {
				photo.setThumbUrl(phoJson.getString("thumbUrl"));
			}
			if (phoJson.opt("imageUrl") != null) {
				photo.setImageUrl(phoJson.getString("imageUrl"));
			}
			if (phoJson.opt("date") != null) {
				photo.setDate(new Date(phoJson.getLong("date")));
			}
			photos.add(photo);
		}
		return photos;
	}

	class DownloadPhotoRequest extends RequestUI {
		private String photoUrl;
		private FanconProgressBar progress;
		private Context mContext;

		public DownloadPhotoRequest(Object key, Activity activity,
				String photoUrl) {
			super(key, activity);
			// TODO Auto-generated constructor stub
			mContext = activity;
			this.photoUrl = photoUrl;
			progress = FanconProgressBar.show(mContext, "");
		}

		@Override
		public void execute() throws Exception {
			// TODO Auto-generated method stub
			downloadFromUrl(photoUrl, String.valueOf(photoUrl.hashCode()));
		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub
			if (progress != null) {
				progress.dismiss();
			}
			String filename = String.valueOf(photoUrl.hashCode());
			File file = new File(StorageUtils.getIndividualCacheDirectory(
					getApplicationContext()).getAbsolutePath()
					+ "/" + filename);
			if (file.exists()) {
				imagePath = StorageUtils.getIndividualCacheDirectory(
						getApplicationContext()).getAbsolutePath()
						+ "/" + filename;
				String html = "<html><head></head><body><center><img src=\""
						+ "file:/" + imagePath + "\"></center></body></html>";
				mWb.loadDataWithBaseURL("", html, "text/html", "utf-8", "");
			}
		}

		public void downloadFromUrl(String DownloadUrl, String fileName) {

			try {
				File dir = StorageUtils
						.getIndividualCacheDirectory(getApplicationContext());
				if (dir.exists() == false) {
					dir.mkdirs();
				}

				URL url = new URL(DownloadUrl); // you can write here any link
				File file = new File(dir, fileName);

				long startTime = System.currentTimeMillis();

				/* Open a connection to that URL. */
				URLConnection ucon = url.openConnection();

				/*
				 * Define InputStreams to read from the URLConnection.
				 */
				InputStream is = ucon.getInputStream();
				BufferedInputStream bis = new BufferedInputStream(is);

				/*
				 * Read bytes to the Buffer until there is nothing more to
				 * read(-1).
				 */
				ByteArrayBuffer baf = new ByteArrayBuffer(50);
				int current = 0;
				while ((current = bis.read()) != -1) {
					baf.append((byte) current);
				}

				/* Convert the Bytes read to a String. */
				FileOutputStream fos = new FileOutputStream(file);
				fos.write(baf.toByteArray());
				fos.flush();
				fos.close();
				Log.d("DownloadManager",
						"download ready in "
								+ ((System.currentTimeMillis() - startTime) / 1000)
								+ " sec");

			} catch (IOException e) {
				Log.d("DownloadManager", "Error: " + e);
			}

		}

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		try {
			if (v == next) {
				Log.d("next", "next");
				if (index < lisPhoto.size()) {
					index++;
					photoUrl = lisPhoto.get(index).getImageUrl();
					loadImage();
				}
			} else if (v == back) {
				Log.d("back", "back");
				if (index > 0) {
					index--;
					photoUrl = lisPhoto.get(index).getImageUrl();
					loadImage();
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
}
